'''
Created on Mar 24, 2010

@author: jhlee
'''
from Vertex3D import Vertex3D
from NumberUV import NumberUV
from Triangle3D import Triangle3D

class Plane:
    def __init__(self, material=None, w=0, h=0, segmentsW=0, segmentsH=0):
        self.segmentsW = segmentsW
        self.segmentsH = segmentsH        
        self.material = material
        
        self.w = w
        self.h = h
        
        self.buildPlane(w, h)
        
    def buildPlane(self, w, h):
        gridX = self.segmentsW
        gridY = self.segmentsH
        
        fgridX = float(gridX)
        fgridY = float(gridY)
        
        gridX1 = gridX + 1
        gridY1 = gridY + 1
        
        stepW = w / gridX
        stepH = -h / gridY
        
        textureX = w / 2
        textureY = h / 2
        
        # Add vertices
        vertices = []        
        for ix in range(gridX + 1):
            for iy in range(gridY + 1):
                x = ix * stepW - textureX
                y = iy * stepH + textureY
                
                vertices.append(Vertex3D(x, y, 0))
        self.vertices = vertices
                
        # Generate faces
        faces = []
        for ix in range(gridX):
            for iy in range(gridY):
                
                # 1st triangle
                a = vertices[ ix * gridY1 + iy    ]
                b = vertices[(ix + 1) * gridY1 + iy    ]
                c = vertices[ ix * gridY1 + iy + 1]
                
                uvA = NumberUV(ix / fgridX, 1.0 - iy / fgridY)
                uvB = NumberUV((ix + 1) / fgridX, 1.0 - iy / fgridY)
                uvC = NumberUV(ix / fgridX, 1.0 - (iy + 1) / fgridY)
                
                faces.append(Triangle3D([a, b, c], self.material, [uvA, uvB, uvC]))
                
                # 2nd triangle
                a = vertices[ (ix + 1) * gridY1 + iy + 1]
                b = vertices[ ix * gridY1 + iy + 1]
                c = vertices[ (ix + 1) * gridY1 + iy    ]
                
                uvA = NumberUV((ix + 1) / fgridX, 1.0 - (iy + 1) / fgridY)
                uvB = NumberUV((ix / fgridX), 1.0 - (iy + 1) / fgridY)
                uvC = NumberUV((ix + 1) / fgridX, 1.0 - iy / fgridY)
                
                faces.append(Triangle3D([a, b, c], self.material, [uvA, uvB, uvC]))
        self.faces = faces
        
                
    def render(self):
        assert(self.material <> None, 'Material should not be null')
        for face in self.faces:
            face.render()
        
